﻿using System;

namespace ZeBobo5.LibraryHelper.Orm
{
    public class OrmField<A, T> : OrmFieldBase<A>
        where A : OrmDataElementBase<A>
    {
        #region Delegates

        public delegate void FieldChangedEventHandler(OrmField<A, T> sender, OrmValues<T> value);

        public delegate void FieldChangingEventHandler(OrmField<A, T> sender, OrmValues<T> value);

        #endregion

        private readonly T _dft;

        public OrmField(string name, T defaultValue)
        {
            FieldName = name;
            _dft = defaultValue;
        }

        //public OrmValues<A> OrmValues
        //{
        //    get
        //    {
        //        throw new NotImplementedException();
        //    }
        //}

        public OrmValues<T> Values(OrmDataElementBase<A> el)
        {
            if (!_ormValues.ContainsKey(el))
            {
                OrmValues<T> val = new OrmValues<T>();
                val.OriginalValue = _dft;
                val.CurrentValue = _dft;
                val.FieldChanging +=
                    delegate
                        {
                            OnFieldChanging(val);
                            el.OnFieldChanging(this);
                        };
                val.FieldChanged +=
                    delegate
                        {
                            OnFieldChanged(val);
                            el.OnFieldChanged(this);
                        };
                _ormValues[el] = val;
            }
            el.AddOwnerField<T>(this);
            return (OrmValues<T>) _ormValues[el];
        }

        public override Type ValuesType()
        {
            return typeof (T);
        }

        public void OnFieldChanging(OrmValues<T> value)
        {
            if (FieldChanging != null)
            {
                FieldChanging(this, value);
            }
        }

        public void OnFieldChanged(OrmValues<T> value)
        {
            if (FieldChanged != null)
            {
                FieldChanged(this, value);
            }
        }

        public event FieldChangingEventHandler FieldChanging;
        public event FieldChangedEventHandler FieldChanged;

    }
}